﻿package ui.components.scroll{
	import flash.display.Sprite
	import flash.display.DisplayObject
	import flash.geom.Rectangle
	import ui.components.Box;
	public class ScrollBox extends Box{
		private var _container:Sprite = new Content();
		private var _mask:Sprite = new Sprite();
		private var _scrollX:Number = 0;
		private var _scrollY:Number = 0;
		
		private var hscroll:ScrollBar = new ScrollBar();
		
		function ScrollBox(){
			super();
			super.addChild(_container)
			super.addChild(_mask);
			super.addChild(hscroll);
			_mask.graphics.beginFill(0x0,1)
			_mask.graphics.drawRect(0,0,100,100);
			_mask.graphics.endFill();
			
			
			hscroll.scroll(function(s:Number):void{
				scrollY = s; 
			});
			
			_container.mask = _mask
		}
		
		public override function add(...args:Array):Box{
			for each(var d:DisplayObject in args)
				_container.addChild(d);

			redraw();
			return this;
		}
		
		
		public function set scrollX(sx:Number):void{
			_scrollX = sx;
			redraw()
		}
		
		public function set scrollY(sy:Number):void{
			hscroll.scrollValue = sy;
			_scrollY = sy;
			redraw();
		}
		public function get scrollWidth():Number{
			return _container.width - _mask.width
		}
		
		public function get scrollHeight():Number{
			return _container.height - _mask.height
		}
		
		public function get scrollX():Number{
			return _scrollX;
		}
		
		public function get scrollY():Number{
			return _scrollY;
		}
		
		public override function get width():Number{
			return _width
		}
		public override function get height():Number{
			return _height 
		}
		
		public override function addChild(d:DisplayObject):DisplayObject{
			return _container.addChild(d);
		}

		public override function removeChild(d:DisplayObject):DisplayObject{
			return _container.removeChild(d);
		}
		
		public function refresh():void{
			redraw();
		}
		
		protected override function redraw():void{
	
			
			var tw:Number = _width
			if(_container.height > _height){
				_width -= 10
				hscroll.visible = true
				hscroll.scrollViewable = _height
				hscroll.scrollSize = _container.height + (_top||0) + (_bottom||0)
					
				
					
			}else{
				hscroll.visible = false;
				hscroll.scrollValue = 0;
			}
			
			super.redraw();
			_scrollX = Math.max( Math.min(_scrollX,scrollWidth), 0);
			_scrollY = Math.max( Math.min(_scrollY,scrollHeight), 0);
			
			
			_container.x -= _scrollX+1
			_container.y -= _scrollY+1
			
			hscroll.x = _width 
			hscroll.y = 0
			hscroll.height = Math.ceil(_height)
			
			_width = tw;
			
			this.scrollRect = new Rectangle(0,0,_width+1,_height+1)
			
		}
		
	}
}

import ui.components.Component
import flash.display.DisplayObject
class Content extends Component{
	protected override function redraw():void{
		for(var a:int=0;a<numChildren;a++){
			var content:DisplayObject = getChildAt(a);
			content.width = _width
		}
	}
}